package com.develophelper.example.mybatis.common.datasource;

import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

/**
 * @author snaildev
 * @date 2020/12/03
 **/
@Configuration
@MapperScan(basePackages = "com.develophelper.example.mybatis.domain.repository",
        annotationClass = Mapper.class, sqlSessionFactoryRef = "exampleSqlSessionFactory")
public class ExampleMybatisConfig {

    @Bean
    @ConfigurationProperties("spring.datasource.hikari.example")
    public DataSource exampleHikariDataSource() {
        return DataSourceBuilder.create().type(HikariDataSource.class).build();
    }

    @Bean
    public SqlSessionFactory exampleSqlSessionFactory(@Qualifier("exampleHikariDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setTypeAliasesPackage("com.develophelper.example.mybatis.domain.entity");
        sqlSessionFactoryBean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/example/*.xml"));
        return sqlSessionFactoryBean.getObject();
    }

    @Bean
    public PlatformTransactionManager exampleTransactionManager(@Qualifier("exampleHikariDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
